﻿/*
' DotNetNuke® - http://www.dotnetnuke.com
' Copyright (c) 2002-2009
' by DotNetNuke Corporation
'
' Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated 
' documentation files (the "Software"), to deal in the Software without restriction, including without limitation 
' the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and 
' to permit persons to whom the Software is furnished to do so, subject to the following conditions:
'
' The above copyright notice and this permission notice shall be included in all copies or substantial portions 
' of the Software.
'
' THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 
' TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
' THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
' CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
' DEALINGS IN THE SOFTWARE.
*/

using System;
using MbUnit.Framework;
using WatiN.Core;
using DotNetNuke.Tests.UI.WatiN.Common;
using Gallio.Framework;
using DotNetNuke.Tests.UI.WatiN.Utilities;
using System.Configuration;
using WatiN.Core.DialogHandlers;
using DotNetNuke.Tests.UI.WatiN.Common.WatiNObjects;
using System.IO;

namespace DotNetNuke.Tests.UI.WatiN.BuildVerification
{
    [TestFixture]
    [DependsOn(typeof(InstallTests))]
    [DependsOn(typeof(UpgradeTests))]
    [DependsOn(typeof(LoginTests))]
    public class UserTests : BVTBase
    {
        #region Test Setup and TearDown

        [SetUp]
        public void SetUp()
        {
            SetUpTest();
        }

        [TearDown]
        public void TearDown()
        {
            TearDownTest();
        }

        #endregion

        #region Tests

        [Test]
        [CsvData(ResourcePath = "TestData.UpgradeList.csv", HasHeader = true)]
        [CsvData(ResourcePath = "TestData.InstallList.csv", HasHeader = true)]
        public void Add_User(string version, string type)
        {
            if (type.Equals("UpgradeOnly"))
            {
                Gallio.Framework.TestLog.WriteLine("This test has not been run on an installation site.");
                Assert.IsTrue(true);
            }
            else if (type.Equals("InstallOnly"))
            {
                Gallio.Framework.TestLog.WriteLine("This test has not been run on an upgraded site.");
                Assert.IsTrue(true);
            }
            else
            {
                //Arrange
                string capturePath = CapturePath + @"\UserTests\AddUser\";
                WatiNAssert watinAssert = new WatiNAssert(ieInstance, capturePath);
                if (!Directory.Exists(capturePath))
                {
                    Directory.CreateDirectory(capturePath);
                }
                WatiNBase homePage = new WatiNBase(ieInstance, SiteURL, DatabaseName);
                LoginPage loginPage = new LoginPage(homePage);
                try
                {
                    loginPage.LoginUser(TestUsers.Admin.UserName, TestUsers.Admin.Password);

                    //Act
                    ieInstance.GoTo(SiteURL + "/Admin/UserAccounts.aspx");
                    System.Threading.Thread.Sleep(2000);
                    if (homePage.PageContainsErrors())
                    {
                        //Take a screen Capture
                        ieInstance.CaptureWebPageToFile(CapturePath + "/ErrorOnUserAccountsPage.jpg");
                        TestLog.WriteHighlighted("WARNING:");
                        TestLog.WriteLine("An error occurred on the User Accounts Page, view the corresponding screen shot and exception text log for more information on the error. ");

                        //Record any recent exceptions in the log
                        loginPage.LogoffUser();
                        loginPage.LoginUser(TestUsers.Host.UserName, TestUsers.Host.Password);
                        ieInstance.GoTo(SiteURL + "/Host/SQL.aspx");
                        HostSQLPage SQLPage = new HostSQLPage(homePage);
                        SQLPage.CheckForRecentExceptionsWriteToFile(CapturePath + "UserAccountsExceptions.txt", SiteType.Equals("Qualifier"));

                        //Log back in as the admin and Continue the test
                        loginPage.LogoffUser();
                        loginPage.LoginUser(TestUsers.Admin.UserName, TestUsers.Admin.Password);
                        ieInstance.GoTo(SiteURL + "/Admin/UserAccounts.aspx");
                    }
                    UserPage userPage = new UserPage(homePage);
                    userPage.AddNewUserStartLink.Click();
                    //Enter User inforrmation
                    userPage.UserNameField.Value = TestUsers.User1.UserName;
                    userPage.FirstNameField.Value = TestUsers.User1.FirstName;
                    userPage.LastNameField.Value = TestUsers.User1.LastName;
                    userPage.DisplayNameField.Value = TestUsers.User1.DisplayName;
                    userPage.EmailField.Value = TestUsers.User1.EmailAddress;
                    userPage.PasswordField.Value = TestUsers.User1.Password;
                    userPage.ConfirmPasswordField.Value = TestUsers.User1.Password;
                    userPage.AddNewUserLink.ClickNoWait();
                    System.Threading.Thread.Sleep(2000);

                    //Assert
                    if (homePage.PageContainsErrors())
                    {
                        //Take a screen Capture
                        ieInstance.CaptureWebPageToFile(CapturePath + "/ErrorOnUserAccountsPage.jpg");
                        TestLog.WriteHighlighted("WARNING:");
                        TestLog.WriteLine("An error occurred on the User Accounts Page, view the corresponding screen shot and exception text log for more information on the error. ");

                        //Record any recent exceptions in the log
                        loginPage.LogoffUser();
                        loginPage.LoginUser(TestUsers.Host.UserName, TestUsers.Host.Password);
                        ieInstance.GoTo(SiteURL + "/Host/SQL.aspx");
                        HostSQLPage SQLPage = new HostSQLPage(homePage);
                        SQLPage.CheckForRecentExceptionsWriteToFile(CapturePath + "UserAccountsExceptions.txt", SiteType.Equals("Qualifier"));

                        //Log back in as the admin and Continue the test
                        loginPage.LogoffUser();
                        loginPage.LoginUser(TestUsers.Admin.UserName, TestUsers.Admin.Password);
                        ieInstance.GoTo(SiteURL + "/Admin/UserAccounts.aspx");
                    }
                    userPage.AllDisplayLink.Click();
                    System.Threading.Thread.Sleep(1000);
                    watinAssert.AssertIsTrue(userPage.UserTable.InnerHtml.Contains(TestUsers.User1.UserName), "UserTable.jpg");
                }
                catch (Exception e)
                {
                    if (!e.ToString().Contains("AssertionFailureException"))
                    {
                        ieInstance.CaptureWebPageToFile(capturePath + "Exception.jpg");
                        Assert.IsTrue(false, "An Exception Occured during the test, view the screen shot for more information. " + System.Environment.NewLine + e.ToString());
                    }
                    else
                    {
                        throw e;
                    }
                }
            }
        }

        [Test]
        [DependsOn("Add_User")]
        [CsvData(ResourcePath = "TestData.UpgradeList.csv", HasHeader = true)]
        [CsvData(ResourcePath = "TestData.InstallList.csv", HasHeader = true)]
        public void Delete_User(string version, string type)
        {
            if (type.Equals("UpgradeOnly"))
            {
                Gallio.Framework.TestLog.WriteLine("This test has not been run on an installation site.");
                Assert.IsTrue(true);
            }
            else if (type.Equals("InstallOnly"))
            {
                Gallio.Framework.TestLog.WriteLine("This test has not been run on an upgraded site.");
                Assert.IsTrue(true);
            }
            else
            {
                //Arrange
                string capturePath = CapturePath + @"\UserTests\DeleteUser\";
                WatiNAssert watinAssert = new WatiNAssert(ieInstance, capturePath);
                if (!Directory.Exists(capturePath))
                {
                    Directory.CreateDirectory(capturePath);
                }
                WatiNBase homePage = new WatiNBase(ieInstance, SiteURL, DatabaseName);
                LoginPage loginPage = new LoginPage(homePage);
                try
                {
                    loginPage.LoginUser(TestUsers.Admin.UserName, TestUsers.Admin.Password);
                    //Assert.IsFalse(homePage.PageContainsErrors());
                    //A user must first be added
                    ieInstance.GoTo(SiteURL + "/Admin/UserAccounts.aspx");
                    if (homePage.PageContainsErrors())
                    {
                        //Take a screen Capture
                        ieInstance.CaptureWebPageToFile(CapturePath + "/ErrorOnUserAccountsPage.jpg");
                        TestLog.WriteHighlighted("WARNING:");
                        TestLog.WriteLine("An error occurred on the User Accounts Page, view the corresponding screen shot and exception text log for more information on the error. ");

                        //Record any recent exceptions in the log
                        loginPage.LogoffUser();
                        loginPage.LoginUser(TestUsers.Host.UserName, TestUsers.Host.Password);
                        ieInstance.GoTo(SiteURL + "/Host/SQL.aspx");
                        HostSQLPage SQLPage = new HostSQLPage(homePage);
                        SQLPage.CheckForRecentExceptionsWriteToFile(CapturePath + "UserAccountsExceptions.txt", SiteType.Equals("Qualifier"));

                        //Log back in as the admin and Continue the test
                        loginPage.LogoffUser();
                        loginPage.LoginUser(TestUsers.Admin.UserName, TestUsers.Admin.Password);
                        ieInstance.GoTo(SiteURL + "/Admin/UserAccounts.aspx");
                    }
                    System.Threading.Thread.Sleep(2000);
                    UserPage userPage = new UserPage(homePage);
                    userPage.AddUser(TestUsers.User1.UserName, TestUsers.User1.Password, TestUsers.User1.FirstName, TestUsers.User1.LastName, TestUsers.User1.EmailAddress, TestUsers.User1.DisplayName);
                    System.Threading.Thread.Sleep(3000);
                    userPage.AllDisplayLink.Click();
                    System.Threading.Thread.Sleep(1000);
                    ConfirmDialogHandler dialog = new ConfirmDialogHandler();

                    //Act 
                    using (new UseDialogOnce(ieInstance.DialogWatcher, dialog))
                    {
                        userPage.GetUserDeleteButton(TestUsers.User1.DisplayName).ClickNoWait();
                        dialog.WaitUntilExists();
                        dialog.OKButton.Click();
                    }
                    System.Threading.Thread.Sleep(5000);

                    //Assert
                    if (homePage.PageContainsErrors())
                    {
                        //Take a screen Capture
                        ieInstance.CaptureWebPageToFile(CapturePath + "/ErrorOnUserAccountsPage.jpg");
                        TestLog.WriteHighlighted("WARNING:");
                        TestLog.WriteLine("An error occurred on the User Accounts Page, view the corresponding screen shot and exception text log for more information on the error. ");

                        //Record any recent exceptions in the log
                        loginPage.LogoffUser();
                        loginPage.LoginUser(TestUsers.Host.UserName, TestUsers.Host.Password);
                        ieInstance.GoTo(SiteURL + "/Host/SQL.aspx");
                        HostSQLPage SQLPage = new HostSQLPage(homePage);
                        SQLPage.CheckForRecentExceptionsWriteToFile(CapturePath + "UserAccountsExceptions.txt", SiteType.Equals("Qualifier"));

                        //Log back in as the admin and Continue the test
                        loginPage.LogoffUser();
                        loginPage.LoginUser(TestUsers.Admin.UserName, TestUsers.Admin.Password);
                        ieInstance.GoTo(SiteURL + "/Admin/UserAccounts.aspx");
                    }
                    userPage.AllDisplayLink.ClickNoWait();
                    System.Threading.Thread.Sleep(1500);
                    watinAssert.AssertIsTrue(userPage.CheckUserDisplaysAsDeleted(TestUsers.User1.DisplayName), "UserTable.jpg");
                    //Log the Amin out 
                    loginPage.LogoffUser();
                    System.Threading.Thread.Sleep(1500);
                    //Attempt to login the deleted user
                    LoginPage userLoginPage = new LoginPage(homePage);
                    userLoginPage.LoginUser(TestUsers.User1.UserName, TestUsers.User1.Password);
                    watinAssert.AssertIsTrue(userLoginPage.LoginMessage.InnerHtml.Contains("Login Failed."), "LoginSuccessful.jpg");
                }
                catch (Exception e)
                {
                    if (!e.ToString().Contains("AssertionFailureException"))
                    {
                        ieInstance.CaptureWebPageToFile(capturePath + "Exception.jpg");
                        Assert.IsTrue(false, "An Exception Occured during the test, view the screen shot for more information. " + System.Environment.NewLine + e.ToString());
                    }
                    else
                    {
                        throw e;
                    }
                }
            }
        }

        [Test]
        [CsvData(ResourcePath = "TestData.UpgradeList.csv", HasHeader = true)]
        [CsvData(ResourcePath = "TestData.InstallList.csv", HasHeader = true)]
        public void Register_User(string version, string type)
        {
            if (type.Equals("UpgradeOnly"))
            {
                Gallio.Framework.TestLog.WriteLine("This test has not been run on an installation site.");
                Assert.IsTrue(true);
            }
            else if (type.Equals("InstallOnly"))
            {
                Gallio.Framework.TestLog.WriteLine("This test has not been run on an upgraded site.");
                Assert.IsTrue(true);
            }
            else
            {
                //Arrange 
                string capturePath = CapturePath + @"\UserTests\RegisterUser\";
                WatiNAssert watinAssert = new WatiNAssert(ieInstance, capturePath);
                if (!Directory.Exists(capturePath))
                {
                    Directory.CreateDirectory(capturePath);
                }
                WatiNBase homePage = new WatiNBase(ieInstance, SiteURL, DatabaseName);
                UserPage userPage = new UserPage(homePage);
                // Assert.IsFalse(homePage.PageContainsErrors());

                //Act
                try
                {
                    userPage.RegisterLink.Click();
                    System.Threading.Thread.Sleep(2000);
                    userPage.UserNameField.Value = TestUsers.Register.UserName;
                    userPage.FirstNameField.Value = TestUsers.Register.FirstName;
                    userPage.LastNameField.Value = TestUsers.Register.LastName;
                    userPage.DisplayNameField.Value = TestUsers.Register.DisplayName;
                    userPage.EmailField.Value = TestUsers.Register.EmailAddress;
                    userPage.PasswordField.Value = TestUsers.Register.Password;
                    userPage.ConfirmPasswordField.Value = TestUsers.Register.Password;
                    userPage.RegisterButton.Click();
                    //No longer need to click proceed to login button
                    //userPage.ProceedToLogin.Click();

                    //Assert
                    System.Threading.Thread.Sleep(2000);
                    if (homePage.PageContainsErrors())
                    {
                        //Take a screen Capture
                        ieInstance.CaptureWebPageToFile(CapturePath + "/ErrorOnUserAccountsPage.jpg");
                        TestLog.WriteHighlighted("WARNING:");
                        TestLog.WriteLine("An error occurred on the User Accounts Page, view the corresponding screen shot and exception text log for more information on the error. ");

                        //Record any recent exceptions in the log
                        LoginPage loginPage = new LoginPage(homePage);
                        loginPage.LogoffUser();
                        loginPage.LoginUser(TestUsers.Host.UserName, TestUsers.Host.Password);
                        ieInstance.GoTo(SiteURL + "/Host/SQL.aspx");
                        HostSQLPage SQLPage = new HostSQLPage(homePage);
                        SQLPage.CheckForRecentExceptionsWriteToFile(CapturePath + "UserAccountsExceptions.txt", SiteType.Equals("Qualifier"));

                        //Log back in as the admin and Continue the test
                        loginPage.LogoffUser();
                        loginPage.LoginUser(TestUsers.Admin.UserName, TestUsers.Admin.Password);
                        ieInstance.GoTo(SiteURL + "/Home.aspx");
                    }
                    watinAssert.AssertIsTrue(userPage.RegisterLink.Text.StartsWith(TestUsers.Register.DisplayName), "UserNotRegistered.jpg");
                }
                catch (Exception e)
                {
                    if (!e.ToString().Contains("AssertionFailureException"))
                    {
                        ieInstance.CaptureWebPageToFile(capturePath + "Exception.jpg");
                        Assert.IsTrue(false, "An Exception Occured during the test, view the screen shot for more information. " + System.Environment.NewLine + e.ToString());
                    }
                    else
                    {
                        throw e;
                    }
                }
            }
        }

        #endregion
    }
}

